// 新闻分类管理

import React, { useState, useRef, useContext, ReactNode, DetailedHTMLProps, HTMLAttributes } from 'react';
import { Button, Table, Modal, Form, Input, Card, Space } from 'antd';
import { DeleteOutlined, ExclamationCircleOutlined, PlusOutlined, EditOutlined } from '@ant-design/icons';
import type { FormInstance } from 'antd/es/form';
import type { InputRef } from 'antd/es/input';
import useCategories from '../../../hooks/useCategories';
import { Category } from '../../../types';
import SimplePermissionButton from '../../../components/permission/SimplePermissionButton';

const { confirm } = Modal;

// 创建可编辑行上下文
const EditableContext = React.createContext<FormInstance | null>(null);

// 定义可编辑行组件
interface EditableRowProps extends DetailedHTMLProps<HTMLAttributes<HTMLTableRowElement>, HTMLTableRowElement> {
  index: number;
}

const EditableRow: React.FC<EditableRowProps> = ({ ...props }) => {
  const [form] = Form.useForm();
  return (
    <Form form={form} component={false}>
      <EditableContext.Provider value={form}>
        <tr {...props} />
      </EditableContext.Provider>
    </Form>
  );
};

// 定义可编辑单元格组件
interface EditableCellProps {
  title: string;
  editable: boolean;
  children: ReactNode;
  dataIndex: string;
  record: Category;
  handleSave: (record: Category) => void;
  [x: string]: unknown;
}

const EditableCell: React.FC<EditableCellProps> = ({
  title,
  editable,
  children,
  dataIndex,
  record,
  handleSave,
  ...restProps
}) => {
  const [editing, setEditing] = useState(false);
  const inputRef = useRef<InputRef>(null);
  const form = useContext(EditableContext);

  React.useEffect(() => {
    if (editing && inputRef.current) {
      inputRef.current.focus();
    }
  }, [editing]);

  const toggleEdit = () => {
    setEditing(!editing);
    form?.setFieldsValue({
      [dataIndex]: record[dataIndex as keyof Category],
    });
  };

  const save = async () => {
    try {
      const values = await form?.validateFields();
      toggleEdit();
      handleSave({ ...record, ...values });
    } catch (errInfo) {
      console.log('Save failed:', errInfo);
    }
  };

  let childNode = children;

  if (editable) {
    childNode = editing ? (
      <Form.Item
        style={{ margin: 0 }}
        name={dataIndex}
        rules={[
          {
            required: true,
            message: `${title}是必填项`,
          },
        ]}
      >
        <Input ref={inputRef} onPressEnter={save} onBlur={save} />
      </Form.Item>
    ) : (
      <div
        className="editable-cell-value-wrap"
        style={{ paddingRight: 24, cursor: 'pointer' }}
        onClick={toggleEdit}
      >
        {children}
      </div>
    );
  }

  return <td {...restProps}>{childNode}</td>;
};

// 新闻分类组件
const NewsCategory: React.FC = () => {
  const [form] = Form.useForm();
  const [modalVisible, setModalVisible] = useState(false);
  const inputRef = useRef<InputRef>(null);

  // 使用自定义钩子获取分类数据和操作方法
  const { categories, loading, updateCategory, deleteCategory, addCategory } = useCategories();
  
  // 处理MongoDB返回的数据
  const processedCategories = React.useMemo(() => {
    return categories.map(category => {
      // 处理MongoDB返回的数据，确保title正确显示
      if (category._doc) {
        return {
          ...category,
          title: category._doc.title || category.title,
          seqId: category._doc.seqId || category.seqId
        };
      }
      return category;
    });
  }, [categories]);

  // 处理保存
  const handleSave = (record: Category) => {
    const { id, _id } = record;
    const categoryId = id || _id;
    
    if (!categoryId) {
      console.error('无法更新分类：找不到有效的ID');
      return;
    }
    
    // 准备更新数据，移除ID字段避免冲突
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const { id: _, _id: __, ...updateData } = record;
    
    // 直接传递原始ID，不进行数字转换
    updateCategory({ 
      id: categoryId, 
      category: updateData 
    });
  };

  // 删除确认
  const confirmDelete = (item: Category) => {
    const categoryId = item.id || item._id;
    if (!categoryId) {
      console.error('无法删除分类：找不到有效的ID');
      return;
    }
    
    confirm({
      title: '你确定要删除?',
      icon: <ExclamationCircleOutlined />,
      content: '此操作不可逆，请谨慎操作',
      onOk() {
        // 直接传递原始ID，不进行数字转换
        deleteCategory(categoryId);
      }
    });
  };

  // 添加新分类
  const handleAdd = async () => {
    try {
      const values = await form.validateFields();
      await addCategory(values);
      setModalVisible(false);
      form.resetFields();
    } catch (error) {
      console.error('添加分类失败:', error);
    }
  };

  const columns = [
    {
      title: 'ID',
      dataIndex: 'seqId',
      width: 80,
      render: (seqId: string | number, record: Category) => {
        // 确保显示_doc中的seqId
        const displayId = record._doc?.seqId || record.seqId || record.id;
        return <b>{displayId}</b>;
      }
    },
    {
      title: '栏目名称',
      dataIndex: 'title',
      onCell: (record: Category) => ({
        record,
        editable: true,
        dataIndex: 'title',
        title: '栏目名称',
        handleSave
      })
    },
    {
      title: '操作',
      width: 120,
      render: (_: unknown, record: Category) => (
        <Space>
          <Button
            type="primary"
            shape="circle"
            icon={<EditOutlined />}
            title="编辑"
            onClick={() => {
              const cell = document.querySelector(
                `tr[data-row-key="${record._doc?.seqId || record.seqId || record.id}"] td.ant-table-cell:nth-child(2)`
              );
              if (cell) {
                (cell as HTMLElement).click();
              }
            }}
          />
          <SimplePermissionButton
            danger
            shape="circle"
            icon={<DeleteOutlined />}
            onClick={() => confirmDelete(record)}
            permission="delete.news.category"
            disableOnNoPermission={false}
            tooltipTitle="删除分类"
            disabled={record.value === 'uncategorized'} // 防止删除默认分类
          />
        </Space>
      )
    }
  ];

  return (
    <Card
      title="新闻分类管理"
      extra={
        <SimplePermissionButton
          type="primary"
          icon={<PlusOutlined />}
          onClick={() => setModalVisible(true)}
          permission="add.news.category"
          tooltipTitle="添加分类"
        >
          添加分类
        </SimplePermissionButton>
      }
    >
      <Table
        components={{
          body: {
            row: EditableRow,
            cell: EditableCell,
          },
        }}
        rowClassName={() => 'editable-row'}
        bordered
        rowKey={record => String(record._doc?.seqId || record.seqId || record.id || record._id)}
        dataSource={processedCategories}
        columns={columns}
        pagination={{
          pageSize: 10,
          showTotal: total => `共 ${total} 项`,
        }}
        loading={loading}
      />

      <Modal
        title="添加新闻分类"
        open={modalVisible}
        onOk={handleAdd}
        onCancel={() => {
          setModalVisible(false);
          form.resetFields();
        }}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="title"
            label="分类名称"
            rules={[
              { required: true, message: '请输入分类名称' },
              { min: 2, message: '分类名称最少2个字符' },
              { max: 20, message: '分类名称最多20个字符' }
            ]}
          >
            <Input 
              ref={inputRef}
              placeholder="请输入分类名称" 
              autoComplete="off"
              onFocus={() => {
                setTimeout(() => inputRef.current?.focus(), 0);
              }}
            />
          </Form.Item>
        </Form>
      </Modal>
    </Card>
  );
};

export default NewsCategory; 